package com.jr.dao.impl;

import com.jr.vo.ShowBook;
import com.jr.dao.IBookManagerDao;
import com.jr.pojo.Book;
import com.jr.util.DBHelper;
import com.jr.util.PageHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedList;

public class BookManagerDaoImpl implements IBookManagerDao {
    DBHelper db = new DBHelper();
    @Override
    public ArrayList<ShowBook> selectByBook(ShowBook b, PageHelper ph) {
        StringBuilder sb = new StringBuilder("select bookcode,bookname,booktype,bookauthor,publishpress,isborrow" +
                " from book where 1=1  ");

        LinkedList list =new LinkedList();
        if(b.getBooktype()!=null&&b.getBooktype()>0){
            sb.append(" and booktype=?");
            list.add(b.getBooktype());
        }
        if(b.getBookname()!=null&&!b.getBookname().equals("")){
            sb.append(" and bookname like ?");
            list.add("%"+b.getBookname()+"%");
        }
        if(b.getIsborrow()!=null&&b.getIsborrow()>=0){
            sb.append(" and isborrow=?");
            list.add(b.getIsborrow());
        }
        sb.append(" ORDER BY creationtime desc ");
        sb.append(" limit ?,?");
       /*"*/
        int index = (ph.getPageIndex()-1)*ph.getShowNumber();
        if(index<0){
            index=0;
        }
        list.add(index);
        list.add(ph.getShowNumber());


        return db.dtQuery(sb.toString(),ShowBook.class,list.toArray());
    }

    @Override
    public int selectBookCount(ShowBook b) {
        StringBuilder sb = new StringBuilder("select count(*)" +
                " from book where 1=1 ");

        LinkedList list =new LinkedList();
        if(b.getBooktype()!=null&&b.getBooktype()>0){
            sb.append(" and booktype=?");
            list.add(b.getBooktype());
        }
        if(b.getBookname()!=null&&!b.getBookname().equals("")){
            sb.append(" and bookname like ");
            list.add("%"+b.getBookname()+"%");
        }
        if(b.getIsborrow()!=null&&b.getIsborrow()>=0){
            sb.append(" and isborrow=? ");
            list.add(b.getIsborrow());
        }
        Connection con = db.getCon();
        PreparedStatement ps=null;
        ResultSet rs=null;
        try{
            ps = con.prepareStatement(sb.toString());
            if(list.size()>0) {
                for (int i = 0; i < list.size(); i++) {
                    ps.setObject(i + 1, list.get(i));
                }
            }
            rs= ps.executeQuery();
            if(rs.next()){
                return  rs.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            db.closeAll(con,ps,rs);
        }
        return 0;
    }
}
